<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                style="width: 100%"
                :src="row.staffPhoto"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                类型：{{ formatData(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" prop="timeOfEntry" />
            <!-- <el-table-column label="账户状态" /> -->
            <el-table-column label="操作" width="280">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                >查看详情</el-button>
                <el-button type="text" size="small">分配角色</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="hDel(row.id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table-column></el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页 -->
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2, 5, 10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees @close="showDialog = false" @success="hSuccess" />
      </el-dialog>
      <!-- 生成二维码图片的组件 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { delEmployees, getEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addEmployees from './empDialog.vue'
import QRCode from 'qrcode'

// const hireType = {} // {1：正式 2：非正式}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })

const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: {
    addEmployees
  },
  data() {
    return {
      list: [],
      page: 1, // 页码值
      size: 5, // 每一页显示的条数
      total: 0,
      showDialog: false,
      showCodeDialog: false // 二维码查看弹框显示隐藏
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 发送请求获取数据
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log(res, 'getEmployees')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
        this.$message.error('加载员工数据失败')
      }
    },
    formatData(id) {
      console.log(id, 'id')
      return hireType[id] || '未知'
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployees()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployees()
    },
    hSuccess() {
      this.total++
      // 计算出最大页码值
      const maxPage = Math.ceil(this.total / this.size)
      // 把页码值翻到最后一页
      this.page = maxPage
      // 关闭弹层
      this.showDialog = false
      // 重新渲染
      this.loadEmployees()
    },
    // 删除
    hDel(id) {
      this.$confirm('您确定要删除吗，是否继续？', '提示', {
        confirmButtonText: '确定',
        concelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 确定删除
          const res = await delEmployees(id)
          console.log(res)
          if (res.code === 10000) {
            this.$message.success(res.message)
            if (this.list.length === 1) {
              this.page--
              if (this.page <= 0) {
                this.page = 1
              }
            }
            this.loadEmployees()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 导出
    exportExcel() {
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then((excel) => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        const { tHeader, data } = this.transZhKeyToExcel(this.list)
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        import('@/vendor/Export2Excel').then((excel) => {
          // excel指的是模块对象 那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      })
    },
    transZhKeyToExcel(list) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 1 生成表头
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map((enkey) => {
        return mapInfo[enkey]
      })
      // 2 生成表的内容
      const data = list.map((item) => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    // 生成二维码函数
    showCode(url) {
      console.log(url, 'url')
      if (url) {
        this.showCodeDialog = true // 二维码弹框显示
        // 生成二维码图片
        this.$nextTick(() => {
          const res = this.$refs.myCanvas
          console.log(res)
          QRCode.toCanvas(res, url)
        })
      } else {
        this.$message.error('请传入正确的图片')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
